<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/7/24
 * Time: 5:01 PM
 */

namespace App\Services;

use App\Models\WechatBookRecord;

class BookRecordService
{

    /*
     * 获取列表
     */
    public function getList($params)
    {
        $pageSize = $params['page_size'] ?? 50;
        $media    = $params['media'] ?? '';
        $bookName = $params['book_name'] ?? '';

        $query = WechatBookRecord::query();
        if ($media) {
            $query->where('media', 'like', '%' . $media . '%');
        }
        if (!UtilityService::isRoot()) {
            $query->where('admin_id', request()->admin->id);
        }
        if ($bookName) {
            $query->where('book_name', 'like', '%' . $bookName . '%');
        }

        return $query->paginate($pageSize);
    }


    /**
     * 更新书籍记录
     *
     * @param $params
     * @return bool
     */
    public function save($params)
    {
        $id                  = $params['id'] ?? '';
        $media               = $params['media'] ?? '';
        $book_app            = $params['book_app'] ?? '';
        $book_name           = $params['book_name'] ?? '';
        $type                = $params['type'] ?? '';
        $author              = $params['author'] ?? '';
        $book_number         = $params['book_number'] ?? '';
        $is_ambiguous        = $params['is_ambiguous'] ?? 0;
        $is_end              = $params['is_end'] ?? 0;
        $stuck_point_chapter = $params['stuck_point_chapter'] ?? '';
        $recharge_template   = $params['recharge_template'] ?? '';
        $book_money          = $params['book_money'] ?? '';
        $link                = $params['link'] ?? '';
        $remark              = $params['remark'] ?? '';

        $record = $id ? WechatBookRecord::query()->find($id) : new WechatBookRecord();

        $record->admin_id            = request()->admin->id;
        $record->media               = $media;
        $record->book_app            = $book_app;
        $record->book_name           = $book_name;
        $record->type                = $type;
        $record->author              = $author;
        $record->book_number         = $book_number;
        $record->is_ambiguous        = $is_ambiguous;
        $record->is_end              = $is_end;
        $record->stuck_point_chapter = $stuck_point_chapter;
        $record->recharge_template   = $recharge_template;
        $record->book_money          = $book_money;
        $record->link                = $link;
        $record->remark              = $remark;

        return $record->save();
    }
}
